<template>
    <div style="height:100%;">
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>电商管理</div>
          /
          <div class='content-title-child'>标签管理</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <!--表格筛选条件-->
      <el-row style="margin-top:10px" class='labelClass'>
        <el-form v-model="filterFormTo" ref="filterFormTo":inline="true">
          <el-form-item label="分类筛选：" style=""> <!--@change="changeCategory('filterFormTo')"-->
            <el-select v-model="filterFormTo.classId" clearable placeholder="请选择" @change="changeCategory('filterFormTo')">
                <el-option
                  v-for="item in categoryList"
                  :key="item.classId"
                  :value="item.classId"
                  :label="item.className">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="float:right;margin-right:20px">
            <el-button type="primary" @click="addVisable = true">添加</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!--查询表格数据-->
      <el-row>
        <el-table 
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          :data="filterFormFro.tableData" 
          :border="true"
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="index" label="序号"  width="200">
            </el-table-column>
            <el-table-column prop="labelName" label="标签"  width="200">
            </el-table-column>
            <el-table-column prop="sortNum" label="排序编号" width="100">
            </el-table-column>
            <el-table-column prop="sonNum" label="数量" width="100">
            </el-table-column>
            <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 表格下方分页 -->
      <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
            <el-pagination
              @current-change="handleCurrentChange"
              background
              :current-page="filterFormTo.currentPage"
              :page-size="15"
              layout="total, prev, pager, next"
              :page-count="filterFormFro.totalPage">
            </el-pagination>
        </div>
      </el-row>
      <!-- 添加标签信息弹窗 -->
      <el-dialog title="增加标签:"   :visible.sync="addVisable"
          :closeOnClickModal="false" 
          width="500px"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          class="categoryManaDialog"
          @close="resetForm('addForm')">
        <el-form :model='addForm' :rules="addRules" ref="addForm">
            <el-form-item label="标签名称：" :label-width="formLabelWidth" prop="labelName">
              <el-input style='width:240px' @keyup.native="addForm.labelName=addForm.labelName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" v-model.trim="addForm.labelName"></el-input>
            </el-form-item>
            <el-form-item label="排序编号：" :label-width="formLabelWidth" prop="sortNum">
              <el-input style='width:240px' v-model="addForm.sortNum"  type="number"></el-input>
            </el-form-item>
            <el-form-item label="所属分类：" :label-width="formLabelWidth" prop="classId">
              <el-select style="width:240px" v-model="addForm.classId" clearable placeholder="请选择" @change="changeCategory2('addForm')">
                  <el-option
                      v-for="item in categoryList"
                      :key="item.classId"
                      :label="item.className"
                      :value="item.classId">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
              <el-button type="primary" @click="submitAdd()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑表情信息弹窗 -->
      <el-dialog title="编辑标签信息:"   :visible.sync="editVisable"
        :closeOnClickModal="false" 
        width="500px"
        class="categoryManaDialog"
        :close-on-click-modal="false" 
        :close-on-press-escape="false"
        @close="resetForm('editForm')">
        <el-form :model='editForm' ref="editForm" :rules="editRules">
            <el-form-item label="标签名称：" :label-width="formLabelWidth" prop="labelName">
              <el-input style='width:240px' @keyup.native="editForm.labelName=editForm.labelName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')"  v-model.trim="editForm.labelName"></el-input>
            </el-form-item>
            <el-form-item label="排序编号：" :label-width="formLabelWidth" prop="sortNum">
              <el-input style='width:240px' v-model="editForm.sortNum"  type="number"></el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
              <el-button type="primary"  @click="submitEdit()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
    </div>
</template>
<style>
</style>

<script>
import '../../../static/css/businessPlat/labelMana.css'
import '../../../static/css/businessPlat/common.css'
import apiBus from '../../api/businessPlat/apiBus.js'
export default {
  created () {
  },
  mounted () {
    this.getAllClassFro()
    this.getLabelListFro()
    this.tableWidth = document.body.scrollWidth - 259 - 20
  },
  data () {
    var checkNumber = (rule, value, callback) => { // 分类排序编号验证
      if (value > 99) {
        callback(new Error('分类排序编号最大为99'))
      } else {
        callback()
      }
    }
    var checkInetger = (rule, value, callback) => { // 整数验证
      if (value % 1 === 0 && value > 0) {
        callback()
      } else {
        callback(new Error('请输入正整数'))
      }
    }
    return {
      Note: '',
      loadingText: '正在拼命加载中，请稍等......',
      loading: false,
      pointVisible: false,
      paginationVisible: false, // 分页是否显示
      testData: [],
      tableWidth: '', // 表格宽度
      testData2: [],
      filterFormTo: {
        classId: '', // 筛选类型
        currentPage: 1, // 当前页数
        pageSize: 20 // 页面大小
      },
      filterFormFro: {
        tableData: [],
        totalPage: 30 // 总共页数
      },
      categoryList: [],
      noteVisible: false,
      formLabelWidth: '150px',
      addForm: {
        labelName: '', // 标签名称
        sortNum: '', // 排序编号
        classId: '' // 所属分类
      },
      addVisable: false,
      editVisable: false,
      editForm: {
        index: 0,
        labelName: '',
        sonNum: '',
        sortNum: '',
        classId: '' // 所属分类
      },
      deleteForm: {
        labelName: '',
        sonNum: '',
        sortNum: '',
        index: 0,
        labelId: ''
      },
      addRules: { // 弹窗添加标签信息验证规则
        labelName: [
          { required: true, message: '请填写标签名称', trigger: 'blur' },
          { max: 8, message: '标签名称最多8个字', trigger: 'blur' }
        ],
        sortNum: [
          { required: true, message: '请填写排序编号', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        classId: [
          { required: true, message: '请选择所属分类', trigger: 'change' }
        ]
      },
      editRules: { // 弹窗添加标签信息验证规则
        labelName: [
          { required: true, message: '请填写标签名称', trigger: 'blur' },
          { max: 8, message: '标签名称最多8个字', trigger: 'blur' }
        ],
        sortNum: [
          { required: true, message: '请填写排序编号', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /** 提交后台相关函数 */
    // 查询电商标签管理处的电商分类下拉菜单的显示接口
    getAllClassFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllClass(para).then(res => {
        this.categoryList = []
        if (res.data.body.result === 1000) {
          this.categoryList = res.data.body.content.list
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 查看标签列表
    getLabelListFro () {
      this.loading = true
      this.paginationVisible = false
      this.filterFormFro.tableData = []
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          classId: parseInt(this.filterFormTo.classId), // 筛选类型
          pageNum: parseInt(this.filterFormTo.currentPage) // 当前页面数
        })
      }
      apiBus.getLabelList(para).then(res => {
        console.log('getLabelList')
        console.log(res)
        this.loading = false
        if (res.data.body.result === 1000) {
          if (res.data.body.content.list.length > 0) {
            let resData = res.data.body.content.list
            this.filterFormFro.tableData = resData
            for (let i = 0; i < resData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterFormTo.currentPage) - 1) * 15 + i + 1
              this.filterFormFro.tableData[i].labelName = resData[i].labelName
              this.filterFormFro.tableData[i].sortNum = resData[i].sortNum
              this.filterFormFro.tableData[i].sonNum = resData[i].sonNum
              this.filterFormFro.tableData[i].classId = resData[i].classId
              this.filterFormFro.tableData[i].labelId = resData[i].labelId
              this.filterFormFro.tableData[i].className = resData[i].className
            }
            this.filterFormFro.totalPage = res.data.body.content.allPage
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
            this.$message.success('成功提取数据！')
          } else {
            this.$message.warning('没有任何标签信息')
            this.paginationVisible = false
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
          this.paginationVisible = false
        }
      })
      .catch(error => {
        this.loading = false
        this.paginationVisible = false
        this.$message.error(error)
      })
    },
    // 向后台发送增加标签请求
    addLabelListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          labelName: this.addForm.labelName,
          sortNum: parseInt(this.addForm.sortNum),
          classId: parseInt(this.addForm.classId),
          className: this.addForm.className
        })
      }
      apiBus.addLabelList(para).then(res => {
        this.addVisable = false
        if (res.data.body.result === 1000) {
          this.filterFormTo.currentPage = 1
          this.getLabelListFro()
          this.$message.success('成功添加标签！')
          this.resetForm('addForm')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.addVisable = false
        this.$message.error(error)
      })
    },
    // 编辑标签
    editLabelListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          labelName: this.editForm.labelName,
          sortNum: parseInt(this.editForm.sortNum),
          labelId: parseInt(this.editForm.labelId)
        })
      }
      apiBus.editLabelList(para).then(res => {
        this.editVisable = false
        if (res.data.body.result === 1000) {
          this.$message.success('成功编辑标签')
          this.resetForm('editForm')
          this.filterFormTo.currentPage = 1
          this.getLabelListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.editVisable = false
        this.$message.error(error)
      })
    },
    // 删除标签
    deleteLabelListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'businessManageService_v1'
        }),
        body: JSON.stringify({
          labelId: parseInt(this.deleteForm.labelId)
        })
      }
      apiBus.deleteLabelList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('成功删除标签')
          this.filterFormTo.currentPage = 1
          this.getLabelListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 增加标签，点击“保存”
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addLabelListFro()
        } else {
          return false
        }
      })
    },
    // 编辑标签，点击“保存”
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editLabelListFro()
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterFormTo.currentPage = val
      this.getLabelListFro()
    },
    // 改变分类选择
    changeCategory (Form) {
      this.categoryList.forEach((item) => {
        if (item.classId === this[Form].classId) {
          this.$message.success('分类切换到了' + item.className)
          this[Form].classId = parseInt(item.classId)
        }
      })
      this.filterFormTo.currentPage = 1
      this.getLabelListFro()
    },
    changeCategory2 (Form) {
      this.categoryList.forEach((item) => {
        if (item.classId === this[Form].classId) {
          this[Form].className = item.className
        }
      })
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 点击表格中的编辑按钮
    handleEdit (index, row) {
      this.editForm.index = index
      this.editForm.labelName = row.labelName.trim()
      this.editForm.sonNum = parseInt(this.filterFormFro.tableData[index].sonNum)
      this.editForm.sortNum = parseInt(this.filterFormFro.tableData[index].sortNum)
      this.editForm.labelId = parseInt(this.filterFormFro.tableData[index].labelId)
      this.editVisable = true
    },
    // 点击表格删除按钮
    handleDelete (index, row) {
      this.deleteForm.labelName = row.labelName
      this.deleteForm.sortNum = row.sortNum
      this.deleteForm.sonNum = row.sonNum
      this.deleteForm.labelId = this.filterFormFro.tableData[index].labelId
      if (parseInt(this.deleteForm.sonNum) !== 0) {
        this.$message.warning('该标签下有商家，不能删除')
      } else {
        this.$confirm('确定删除该标签吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteLabelListFro()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    }
  }
}
</script>